<template>
	<z-paging ref="paging"
		v-model="currentList"
		@query="queryList"
		height="100vh"
		:paging-style="{minHeight: '100vh', backgroundColor: '#F5F6F7'}">
		<template #top>
			<view class="navbar">
				<view v-for="(item, index) in collectionTabs" :key="index" class="nav-item"
					:class="{current: isChange === index}" @click="changeNav(index)">
					<text>{{item.name}}</text>
				</view>
			</view>
		</template>

		<!-- 内容区域 -->
		<view class="content-box">
			<view class="tabs-container" :style="{transform: `translateX(-${isChange * 100/3}%)`}">
				<!-- 商家收藏 -->
				<view class="tab-content">
					<view class="list-scroll-content" :class="{'animate-in': isChange === 0}">
						<view class="collection-item" v-for="(item, index) in shopList" :key="index"
							:style="{'--item-index': index}">
							<view class="item-left" @click.stop="goShop(item)">
								<image :src="getShopLogo(item)" mode="aspectFill"></image>
							</view>
							<view class="item-right">
								<view class="title" @click.stop="goShop(item)">{{getShopName(item)}}</view>
								<view class="action">
									<button class="delete-btn" @click.stop="shopDelBtn(item.BusinessId)">
										<uni-icons type="trash" size="16" color="#999"></uni-icons>
									</button>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 商品收藏 -->
				<view class="tab-content">
					<view class="list-scroll-content" :class="{'animate-in': isChange === 1}">
						<view class="collection-item" v-for="(item, index) in list" :key="index"
							:style="{'--item-index': index}">
							<view class="item-left" @click="goGoods(item.Id, item.Type)">
								<image :src="getProductImg(item)" mode="aspectFill"></image>
							</view>
							<view class="item-right">
								<view class="title" @click="goGoods(item.Id, item.Type)">{{item.Name || $t('collection.productName')}}</view>
								<view class="price">¥{{item.ShowPrice || item.BusinessPrice || '-'}}</view>
								<view class="action">
									<button class="delete-btn" @click.stop="delBtn(item.Id)">
										<uni-icons type="trash" size="16" color="#999"></uni-icons>
									</button>
								</view>
							</view>
						</view>
					</view>
				</view>

				<!-- 文章收藏 -->
				<view class="tab-content">
					<view class="list-scroll-content" :class="{'animate-in': isChange === 2}">
						<view class="collection-item" v-for="(item, index) in articleList" :key="index"
							:style="{'--item-index': index}">
							<view class="item-left" @click="goArticle(getArticleId(item))">
								<image :src="getArticleImg(item)" mode="aspectFill"></image>
							</view>
							<view class="item-right article-right">
															<view class="title" @click="goArticle(getArticleId(item))">{{item.Title || $t('collection.articleTitle')}}</view>
							<view class="article-info">
								<text class="article-date">{{formatDate(item.AddTime || item.CreateTime)}}</text>
								<text class="article-views">{{item.ReadCount || 0}}{{$t('collection.readCount')}}</text>
							</view>
								<view class="action">
									<button class="delete-btn" @click.stop="articleDelBtn(getArticleId(item))">
										<uni-icons type="trash" size="16" color="#999"></uni-icons>
									</button>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<template #empty>
			<view class="empty-box">
				<image src="/static/images/empty-box.png" mode="aspectFit"></image>
				<text>{{$t('collection.emptyContent')}}</text>
			</view>
		</template>
	</z-paging>
</template>

<script>
	import {
		getProductCollectionList,
		cancelProductCollection,
		getNewtCollectionList,
		getCancelCollection
	} from '@/api/mall.js'
	import { getCheckCollection } from '@/api/homePage.js'
	import empty from '@/components/empty.vue'

	export default {
		components: {
			empty
		},
		data() {
			return {
				collList: [],
				isChange: 0,
				page: 1,
				list: [],
				shopList: [],
				articleList: [],
				checkKey: 1, // 用于API参数，1=商家，11=商品，2=文章
				currentList: [] // 当前显示的列表
			}
		},
		computed: {
			collectionTabs() {
				return [
					{ name: this.$t('collection.merchant'), Id: 0 },
					{ name: this.$t('collection.product'), Id: 1 },
					{ name: this.$t('collection.article'), Id: 2 }
				];
			}
		},
		onLoad() {
			uni.setNavigationBarTitle({
				title: this.$t('collection.title')
			});
			this.collList = this.collectionTabs;
		},
		methods: {
			// 获取商家Logo
			getShopLogo(item) {
				if (item && item.BusinessModel && item.BusinessModel.ShopLogo) {
					return item.BusinessModel.ShopLogo;
				}
				return '/static/images/default-shop.png';
			},

			// 获取商家名称
			getShopName(item) {
				if (item && item.BusinessModel && item.BusinessModel.ShopName) {
					return item.BusinessModel.ShopName;
				}
				return this.$t('collection.merchantName');
			},

			// 获取商品图片
			getProductImg(item) {
				if (item && item.Img) {
					return item.Img;
				}
				return '/static/images/default-product.png';
			},

			// 获取文章ID
			getArticleId(item) {
				if (item) {
					return item.ArticleId || item.Id;
				}
				return '';
			},

			// 获取文章图片
			getArticleImg(item) {
				if (item && item.ImgUrl) {
					return item.ImgUrl;
				}
				if (item && item.CoverImg) {
					return item.CoverImg;
				}
				return '/static/images/default-article.png';
			},

			// 切换导航
			changeNav(index) {
				if (index !== this.isChange) {
					this.isChange = index;
					// 根据选项卡设置收藏类型
					switch(index) {
						case 0:
							this.checkKey = 1; // 商家
							break;
						case 1:
							this.checkKey = 11; // 商品
							break;
						case 2:
							this.checkKey = 2; // 文章
							break;
					}
					this.$refs.paging.reload();
				}
			},

			// 获取列表数据
			async queryList(pageNo, pageSize) {
				try {
					uni.showLoading({
						title: this.$t('myComplaint.loading'),
						mask: true
					});

					const { Data } = await getNewtCollectionList({
						Index: pageNo,
						Size: pageSize,
						CollectionType: this.checkKey
					});

					if (!Data || !Array.isArray(Data)) {
						console.error('API返回数据格式错误', Data);
						uni.hideLoading();
						this.$refs.paging.complete([]);
						return;
					}

					let resultList = [];
					console.log('收藏数据类型:', this.checkKey, Data);

					switch (this.checkKey) {
						case 1: // 商家
							this.shopList = Data.map(item => ({
								...item,
								BusinessModel: item.BusinessModel || {},
								BusinessId: item.BusinessId || (item.BusinessModel ? item.BusinessModel.BusinessId : '') || item.Id
							}));
							resultList = this.shopList;
							break;

						case 11: // 商品
							this.list = Data.map(item => {
								// 简化商品数据处理逻辑
								if (item && item.ProductModel) {
									return {
										...item.ProductModel,
										Id: item.ProductModel.Id || item.Id,
										Cid: item.Id
									};
								} else {
									return {
										...item,
										Id: item.Id || '',
										Name: item.Name || '商品名称',
										Img: item.Img || '',
										ShowPrice: item.ShowPrice || item.BusinessPrice || 0
									};
								}
							});
							resultList = this.list;
							break;

						case 2: // 文章
							this.articleList = Data.map(item => {
								// 确保返回文章数据使用正确的结构
								if (item && item.ArticleModel) {
									return {
										...item.ArticleModel,
										ArticleId: item.ArticleModel.Id || item.ArticleId || item.Id,
										Cid: item.Id
									};
								} else {
									return {
										...item,
										ArticleId: item.Id || '',
										Title: item.Title || '文章标题'
									};
								}
							});
							resultList = this.articleList;
							break;
					}

					uni.hideLoading();
					this.$refs.paging.complete(resultList);
				} catch (e) {
					console.error('获取列表数据失败:', e);
					uni.hideLoading();
					this.$refs.paging.complete(false);
				}
			},

			// 删除商家收藏
			async shopDelBtn(id) {
				uni.showModal({
					title: this.$t('common.tips'),
					content: this.$t('collection.cancelCollectionConfirm'),
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({ title: this.$t('collection.processing') });
							try {
								await cancelProductCollection({
									Id: id,
									CollectionType: 1
								});
								uni.showToast({
									title: this.$t('collection.canceledCollection'),
									icon: 'none'
								});
								this.$refs.paging.reload();
							} catch (e) {
								console.error('取消收藏失败', e);
								uni.showToast({
									title: this.$t('collection.operationFailed'),
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 删除商品收藏
			async delBtn(id) {
				uni.showModal({
					title: this.$t('common.tips'),
					content: this.$t('collection.cancelCollectionConfirm'),
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({ title: this.$t('collection.processing') });
							try {
								await getCancelCollection({
									Id: id,
									CollectionType: 11
								});
								uni.showToast({
									title: this.$t('collection.canceledCollection'),
									icon: 'none'
								});
								this.$refs.paging.reload();
							} catch (e) {
								console.error('取消收藏失败', e);
								uni.showToast({
									title: this.$t('collection.operationFailed'),
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 删除文章收藏
			async articleDelBtn(id) {
				uni.showModal({
					title: this.$t('common.tips'),
					content: this.$t('collection.cancelCollectionConfirm'),
					success: async (res) => {
						if (res.confirm) {
							uni.showLoading({ title: this.$t('collection.processing') });
							try {
								await getCancelCollection({
									Id: id,
									CollectionType: 2
								});
								uni.showToast({
									title: this.$t('collection.canceledCollection'),
									icon: 'none'
								});
								this.$refs.paging.reload();
							} catch (e) {
								console.error('取消收藏失败', e);
								uni.showToast({
									title: this.$t('collection.operationFailed'),
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					}
				});
			},

			// 跳转到商品详情
			goGoods(id, type) {
				if (!id) {
					uni.showToast({
						title: this.$t('collection.productIncomplete'),
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: `/mall_subpages/goods/index?id=${id}&type=${type || 3}`
				});
			},

			// 跳转到商家详情
			goShop(item) {
				if (!item || !item.BusinessId) {
					uni.showToast({
						title: this.$t('collection.merchantIncomplete'),
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: `/mall_subpages/merchants/detail?id=${item.BusinessId}&type=3`
				});
			},

			// 跳转到文章详情
			goArticle(id) {
				if (!id) {
					uni.showToast({
						title: this.$t('collection.articleIncomplete'),
						icon: 'none'
					});
					return;
				}
				uni.navigateTo({
					url: `/scenicSpot_subpages/raiders/detail?id=${id}`
				});
			},

			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';

				// 如果是日期字符串，转成 YYYY-MM-DD 格式
				if (typeof dateStr === 'string') {
					const parts = dateStr.split(' ')[0].split('-');
					if (parts.length >= 3) {
						return `${parts[0]}-${parts[1]}-${parts[2]}`;
					}
				}

				return dateStr;
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 导航栏样式 */
	.navbar {
		display: flex;
		height: 98rpx;
		background: #FFFFFF;
		position: relative;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 28rpx;
			color: #666;
			position: relative;
			transition: all 0.3s ease;

			text {
				display: inline-block;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
				position: relative;
			}

			&.current {
				text {
					font-size: 32rpx;
					font-weight: 600;
					background-color: #00BFFF;
					color: #FFFFFF;
					transform: translateY(0) scale(1);
					animation: popIn 0.4s ease;
				}
			}
		}
	}

	/* 内容区域样式 */
	.content-box {
		position: relative;
		width: 100%;
		overflow: hidden;
	}

	.tabs-container {
		display: flex;
		width: 300%; /* 三个选项卡，宽度设为300% */
		transition: transform 0.4s cubic-bezier(0.23, 1, 0.32, 1);
		will-change: transform;
	}

	.tab-content {
		flex: 0 0 33.33%; /* 每个选项卡占1/3 */
		width: 33.33%;
	}

	.list-scroll-content {
		padding: 24rpx;
		opacity: 0;
		transform: translateY(30rpx);
		transition: all 0.6s cubic-bezier(0.19, 1, 0.22, 1);

		&.animate-in {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.collection-item {
		background-color: #fff;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		display: flex;
		padding: 24rpx;
		animation: fadeInUp 0.5s ease forwards;
		animation-delay: calc(0.1s * var(--item-index, 0));
		will-change: transform, opacity;
		box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);

		.item-left {
			width: 180rpx;
			height: 180rpx;
			margin-right: 24rpx;
			border-radius: 12rpx;
			overflow: hidden;

			image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
		}

		.item-right {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: space-between;

			.title {
				font-size: 32rpx;
				color: #333;
				font-weight: 600;
				line-height: 1.4;
				margin-bottom: 16rpx;
				/* 文本超出两行省略 */
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.price {
				font-size: 36rpx;
				color: #00BFFF;
				font-weight: 600;
			}

			.action {
				display: flex;
				justify-content: flex-end;

				.delete-btn {
					background: none;
					border: none;
					padding: 10rpx;
					margin: 0;
					line-height: 1;

					&:after {
						border: none;
					}
				}
			}
		}

		/* 文章右侧区域特殊样式 */
		.article-right {
			.article-info {
				display: flex;
				align-items: center;
				margin-bottom: 16rpx;

				.article-date {
					font-size: 24rpx;
					color: #999;
					margin-right: 20rpx;
				}

				.article-views {
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}

	/* 空状态样式 */
	.empty-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 0;

		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}

		text {
			font-size: 28rpx;
			color: #999;
		}
	}

	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(30rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	@keyframes popIn {
		0% {
			transform: translateY(10rpx) scale(0.9);
			opacity: 0.7;
		}
		70% {
			transform: translateY(-5rpx) scale(1.05);
		}
		100% {
			transform: translateY(0) scale(1);
		}
	}
</style>
